import React,{
    ReactNode,
    Children,
    PureComponent
} from 'react';

import {
    View,
    StyleSheet
} from 'react-native';

import TabContent from './content';

import ViewPager from '@react-native-community/viewpager';

interface State {
    curPage: number
}

interface Props {
    page: number,
    locked: boolean,
    animation: boolean,
    onChange: Function,
    tabBarComponent: Function
}

class Tabs extends PureComponent<Props, State> {
    static defaultProps = {
        page: 0,
        locked: false,
        animation: true,
        onChange: () => null,
        tabBarComponent: () => null
    }

    page: number = 0;
    created: any = null;
    timers: Array<number> = [];
    viewPager: ViewPager | any = null;

    constructor(props: Props) {
        super(props);
        this.page = props.page || 0;
    }

    componentDidUpdate() {
        const {
            page
        } = this.props;
        if (this.page !== page) {
            this.page = page;
            this.emitPageChange(page);
        }
    }

    private emitPageChange = (page: number) => {
        const {
            animation
        } = this.props;
        const handel = animation ? `setPage`:
            `setPageWithoutAnimation`;
        this.viewPager[handel](page);
    }

    get Content() {
        const {
            children
        } = this.props;
        return Children.map(
            children, this.renderPage
        )
    }

    private renderPage = (
        child: ReactNode, _page: number
    ) => {
        const {
            page
        } = this.props;
        return (
            <View style={styles.content}>
                <TabContent
                    page={_page}
                    children={child}
                    selectedPage={page}
                />
            </View>
        )
    }

    onPageSelected = ({nativeEvent}: any) => {
        const {
            position
        } = nativeEvent;
        if (this.page !== position) {
            this.page = position;
            this.props.onChange(position)
        }
    }

    render() {
        const {
            locked,
            tabBarComponent
        } = this.props;

        const footerNode = (
            tabBarComponent()
        )

        return (
            <View style={styles.container}>
                <ViewPager
                    children={this.Content}
                    initialPage={this.page}
                    scrollEnabled={!locked}
                    style={styles.container}
                    ref={e => this.viewPager = e}
                    onPageSelected={this.onPageSelected}
                />
                {footerNode}
            </View>
        )
    }
}

export default Tabs;

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    content: {
        flex: 1
    }
}) as any;

